package ohc.login.mixin;

import net.minecraft.network.packet.c2s.play.PlayerInteractEntityC2SPacket;
import net.minecraft.network.packet.c2s.play.PlayerInteractItemC2SPacket;
import net.minecraft.server.network.ServerPlayNetworkHandler;
import net.minecraft.server.network.ServerPlayerEntity;
import net.minecraft.text.Text;
import net.minecraft.util.Formatting;
import ohc.login.LoginManager;
import org.spongepowered.asm.mixin.Mixin;
import org.spongepowered.asm.mixin.Shadow;
import org.spongepowered.asm.mixin.injection.At;
import org.spongepowered.asm.mixin.injection.Inject;
import org.spongepowered.asm.mixin.injection.callback.CallbackInfo;

/**
 * 阻止未登录玩家与实体、物品交互
 */
@Mixin(ServerPlayNetworkHandler.class)
public class PlayerInteractionMixin {
    
    @Shadow
    public ServerPlayerEntity player;
    
    @Inject(method = "onPlayerInteractEntity", at = @At("HEAD"), cancellable = true)
    private void onPlayerInteractEntity(PlayerInteractEntityC2SPacket packet, CallbackInfo ci) {
        if (!LoginManager.INSTANCE.isLoggedIn(player.getUuid())) {
            sendNotLoggedInMessage();
            ci.cancel();
        }
    }
    
    @Inject(method = "onPlayerInteractItem", at = @At("HEAD"), cancellable = true)
    private void onPlayerInteractItem(PlayerInteractItemC2SPacket packet, CallbackInfo ci) {
        if (!LoginManager.INSTANCE.isLoggedIn(player.getUuid())) {
            sendNotLoggedInMessage();
            ci.cancel();
        }
    }
    
    private void sendNotLoggedInMessage() {
        boolean needBind = LoginManager.INSTANCE.needsBind(player.getUuid());
        if (needBind) {
            player.sendMessage(
                Text.literal("§c请先使用 /bind <账号> <密码> 绑定账号！").formatted(Formatting.RED),
                true
            );
        } else {
            player.sendMessage(
                Text.literal("§c请先使用 /l <密码> 登录！").formatted(Formatting.RED),
                true
            );
        }
    }
}
